<template>
  <el-dialog title="回款缴费" v-model="visible" width="600px" @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="回款计划信息">
        <el-card v-if="planInfo" shadow="never" class="plan-info-card">
          <div class="plan-info-item">
            <span class="label">应缴费用金额:</span>
            <span class="value">{{ planInfo.amount }}</span>
          </div>
          <div class="plan-info-item">
            <span class="label">已付金额:</span>
            <span class="value">{{ planInfo.paidAmount }}</span>
          </div>
          <div class="plan-info-item">
            <span class="label">剩余金额:</span>
            <span class="value">{{ planInfo.remainingAmount }}</span>
          </div>
          <div class="plan-info-item">
            <span class="label">费用类型:</span>
            <span class="value">{{ planInfo.type }}</span>
          </div>
          <div class="plan-info-item">
            <span class="label">备注: </span>
            <span class="value">{{ planInfo.remake }}</span>
          </div>
        </el-card>
        <div v-else class="loading-text">加载中...</div>
      </el-form-item>

      <el-form-item label="缴费流水" prop="historyId">
        <el-select
          v-model="formData.historyId"
          placeholder="请选择缴费流水记录"
          style="width: 100%"
          @change="handleHistoryChange"
        >
          <el-option
            v-for="history in historyList"
            :key="history.id"
            :label="`金额: ${history.amount} (剩余: ${history.remainingAmount})`"
            :value="history.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="缴费金额" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :min="0"
          :max="maxAllowedAmount"
          controls-position="right"
          style="width: 100%"
          placeholder="请输入缴费金额"
        />
        <div class="amount-info">
          <div>回款计划剩余金额: {{ planRemainingAmount }}</div>
          <div v-if="selectedHistoryRemainingAmount">
            所选流水剩余金额: {{ selectedHistoryRemainingAmount }}
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { getPaymentHistoryList, payment, getOneById } from "@/api/company/info";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  companyId: {
    type: [String, Number],
    required: true,
  },
  planId: {
    type: [String, Number],
    required: true,
  },
});

const emit = defineEmits(["update:modelValue", "success", "close"]);

// 表单引用
const formRef = ref();

// 控制弹窗显示
const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

// 表单数据
const formData = reactive({
  historyId: "",
  amount: null,
});

// 回款计划信息
const planInfo = ref(null);

// 缴费流水列表
const historyList = ref([]);

// 提交状态
const submitLoading = ref(false);

// 所选缴费流水的剩余金额
const selectedHistoryRemainingAmount = computed(() => {
  if (!formData.historyId) return 0;
  const history = historyList.value.find((item) => item.id === formData.historyId);
  return history ? history.remainingAmount : 0;
});

// 回款计划剩余金额
const planRemainingAmount = computed(() => {
  return planInfo.value ? planInfo.value.remainingAmount : 0;
});

// 最大允许输入金额（取所选流水剩余金额和回款计划剩余金额的较小值）
const maxAllowedAmount = computed(() => {
  if (!formData.historyId) return planRemainingAmount.value;
  return Math.min(selectedHistoryRemainingAmount.value, planRemainingAmount.value);
});

// 表单验证规则
const rules = {
  historyId: [{ required: true, message: "请选择缴费流水记录", trigger: "change" }],
  amount: [
    { required: true, message: "请输入缴费金额", trigger: "blur" },
    { type: "number", min: 0.01, message: "缴费金额必须大于0", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && value > maxAllowedAmount.value) {
          callback(new Error(`缴费金额不能超过${maxAllowedAmount.value}`));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 获取回款计划信息
const fetchPlanInfo = async () => {
  try {
    const res = await getOneById(props.planId);
    if (res.code === 200) {
      planInfo.value = res.data;
    } else {
      ElMessage.error("获取回款计划信息失败");
    }
  } catch (error) {
    ElMessage.error("获取回款计划信息异常");
  }
};

// 获取缴费流水列表
const fetchPaymentHistoryList = async () => {
  try {
    const res = await getPaymentHistoryList({
      companyId: props.companyId,
      pageNum: 1,
      pageSize: 100,
    });

    if (res.code === 200) {
      historyList.value = Array.isArray(res.rows) ? res.rows : [];
    } else {
      ElMessage.error("获取缴费流水记录失败");
    }
  } catch (error) {
    ElMessage.error("获取缴费流水记录异常");
  }
};

// 处理选择缴费流水变更
const handleHistoryChange = (historyId) => {
  // 选择流水后清空金额，让用户重新输入
  formData.amount = null;
};

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    submitLoading.value = true;
    try {
      const res = await payment({
        companyId: props.companyId,
        planId: props.planId,
        historyId: formData.historyId,
        amount: formData.amount,
      });

      if (res.code === 200) {
        ElMessage.success("缴费成功");
        emit("success");
        handleClose();
      } else {
        ElMessage.error(res.msg || "缴费失败");
      }
    } catch (error) {
      ElMessage.error("缴费异常");
    } finally {
      submitLoading.value = false;
    }
  });
};

// 关闭弹窗
const handleClose = () => {
  formRef.value.resetFields();
  formData.historyId = "";
  formData.amount = null;
  emit("close");
};

// 监听弹窗显示状态变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      fetchPlanInfo();
      fetchPaymentHistoryList();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.amount-info {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.plan-info-card {
  width: 100%;
}

.plan-info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.plan-info-item .label {
  font-weight: bold;
  margin-right: 10px;
}

.plan-info-item .value {
  flex: 1;
  text-align: right;
}

.loading-text {
  text-align: center;
  color: #999;
}
</style>
